import { fork } from '../utils/process.js'
import config from '../config/index.js'

const forks = {}

export const startAvd = async ctx => {
  const { query } = ctx
  const script = config.rootDir + '/spider/avd/index.js'
  const type = query.type || 'nvd'

  if (forks[type]) {
    ctx.body = {
      code: 0,
      msg: '请勿重复运行',
    }
    return
  }

  forks[type] = fork(script, ['--type', type], {
    exit() {
      forks[type] = null
    },
  })

  ctx.body = {
    code: 0,
  }
}

export const stopAvd = async ctx => {
  const { query } = ctx
  const type = query.type || 'nvd'

  if (forks[type]) {
    const child = forks[type]
    child.kill('SIGTERM')
  }

  ctx.body = {
    code: 0,
  }
}
